#include "preemption.h"

#define LAPS 100

static struct sigaction sig;
static struct itimerval tv;



void timer_reset() {
  tv.it_value.tv_sec = 0;
  tv.it_value.tv_usec = LAPS;
  (&tv.it_interval)->tv_sec = (&tv.it_interval)->tv_usec = 0 ;
  setitimer(ITIMER_PROF, &tv, NULL);
}

void timer_cut() {
  (&tv.it_value)->tv_sec = (&tv.it_value)->tv_usec = 0 ;
  (&tv.it_interval)->tv_sec = (&tv.it_interval)->tv_usec = 0 ;
  setitimer(ITIMER_VIRTUAL, &tv, NULL);
}

int timer(){ 
  puts("preemption......................");
	tv.it_interval.tv_sec= 0;	
	tv.it_interval.tv_usec = LAPS;
	
	tv.it_value.tv_sec = 0;	
	tv.it_value.tv_usec = LAPS;
	
	if (setitimer(ITIMER_VIRTUAL, &tv , NULL) == -1){
		perror("setitimer");
		return -1;
	}
	return 0;
}


int create_sigaction(void (*handler)(int, siginfo_t*, void*), sigset_t *preempt_set){
	memset(&sig, '\0', sizeof(sig));
	sigemptyset(preempt_set);
	
    assert(0 == sigemptyset(preempt_set));
    assert(0 == sigaddset(preempt_set, SIGVTALRM)); 
	


	sig.sa_sigaction = handler;
	assert(!sigemptyset(&sig.sa_mask));
	sig.sa_flags = SA_SIGINFO;
	

	sigaction(SIGVTALRM, &sig, NULL);
	if (sigaction(SIGTERM, &sig, NULL) < 0) {
		perror ("Installing the signal handler");
		return 1;
	}
	
	return 0;
}




